import React, { useEffect, useRef, useState } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';
import { Spin, Result, Button } from 'antd';

interface EnhancedProtectedRouteProps {
  children: React.ReactNode;
  requireAdmin?: boolean;
}

const EnhancedProtectedRoute: React.FC<EnhancedProtectedRouteProps> = ({ 
  children, 
  requireAdmin = false 
}) => {
  const { isAuthenticated, user, isLoading } = useAuthStore();
  const location = useLocation();
  const redirecting = useRef(false);
  const hasCheckedAuth = useRef(false);
  const [redirectReason, setRedirectReason] = useState<string | null>(null);

  // 调试日志函数
  const logDebug = (message: string, data?: any) => {
    if (process.env.NODE_ENV === 'development') {
      console.log(`[EnhancedProtectedRoute] ${message}`, data || '');
    }
  };

  // 调试日志
  useEffect(() => {
    logDebug('检查路由保护状态:', {
      isAuthenticated,
      isLoading,
      user: !!user,
      pathname: location.pathname,
      hasCheckedAuth: hasCheckedAuth.current,
      redirecting: redirecting.current
    });
  }, [isAuthenticated, isLoading, user, location.pathname]);

  // 检测无限重定向循环
  useEffect(() => {
    // 检查是否在短时间内多次重定向到相同路径
    const checkRedirectLoop = () => {
      const redirectHistory = sessionStorage.getItem('redirectHistory');
      const history = redirectHistory ? JSON.parse(redirectHistory) : [];
      
      // 添加当前重定向记录
      const newEntry = {
        path: location.pathname,
        timestamp: Date.now()
      };
      
      // 只保留最近5次重定向记录
      const updatedHistory = [...history.slice(-4), newEntry];
      sessionStorage.setItem('redirectHistory', JSON.stringify(updatedHistory));
      
      // 检查是否在短时间内重定向到相同路径超过3次
      const recentSamePath = updatedHistory.filter(
        entry => entry.path === location.pathname
      );
      
      if (recentSamePath.length >= 3) {
        const timeDiff = newEntry.timestamp - recentSamePath[0].timestamp;
        if (timeDiff < 5000) { // 5秒内
          console.warn('检测到可能的重定向循环');
          return true;
        }
      }
      
      return false;
    };

    // 如果检测到重定向循环，显示错误页面
    if (checkRedirectLoop()) {
      setRedirectReason('检测到页面重定向循环，请联系技术支持');
    }
  }, [location.pathname]);

  // 如果检测到重定向循环，显示错误页面
  if (redirectReason) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#000'
      }}>
        <Result
          status="warning"
          title="页面重定向异常"
          subTitle={redirectReason}
          extra={[
            <Button 
              type="primary" 
              key="home"
              onClick={() => {
                sessionStorage.removeItem('redirectHistory');
                window.location.href = '/';
              }}
            >
              返回首页
            </Button>,
            <Button 
              key="clear"
              onClick={() => {
                sessionStorage.removeItem('redirectHistory');
                sessionStorage.removeItem('auth-store');
                window.location.reload();
              }}
            >
              清除缓存并重试
            </Button>
          ]}
        />
      </div>
    );
  }

  // 如果正在加载，显示加载状态
  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#000'
      }}>
        <Spin size="large" />
        <div style={{ 
          position: 'absolute',
          bottom: '20px',
          color: '#aaa',
          fontSize: '14px'
        }}>
          正在验证用户权限...
        </div>
      </div>
    );
  }

  // 如果未认证，重定向到登录页
  if (!hasCheckedAuth.current && !redirecting.current && !isAuthenticated) {
    logDebug('用户未认证，重定向到登录页');
    hasCheckedAuth.current = true;
    redirecting.current = true;
    setRedirectReason('用户未认证');
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 如果需要管理员权限但用户不是管理员，重定向到首页
  if (!hasCheckedAuth.current && !redirecting.current && requireAdmin && user && !user.is_superuser) {
    logDebug('需要管理员权限但用户不是管理员，重定向到首页');
    hasCheckedAuth.current = true;
    redirecting.current = true;
    setRedirectReason('需要管理员权限');
    return <Navigate to="/dashboard" replace />;
  }

  // 防止重复渲染
  if (!hasCheckedAuth.current) {
    hasCheckedAuth.current = true;
  }

  return <>{children}</>;
};

export default EnhancedProtectedRoute;